#!/usr/bin/env python
# -*- coding:utf-8 -*-


import os
from logging.handlers import RotatingFileHandler
from datetime import date
import logging

from _log_json_format import JsonFileFormater, ConsoleFormater

PATH="py_log/"
BASIC_FORMAT =  "%(asctime)s [%(levelname)s] [%(pathname)s] [%(threadName)s:%(thread)d] [%(name)s:%(lineno)d] - %(message)s"


def assure_path_exists(path):
    dir = os.path.dirname(path)
    if not os.path.exists(dir):
        os.makedirs(dir)
assure_path_exists(PATH)

def get_info_handler():
    filename = PATH + "info-" + date.today().isoformat() + ".log"
    fr = JsonFileFormater(BASIC_FORMAT)
    info_handler = RotatingFileHandler(
        filename,
        maxBytes= 10*1024*1024,
        backupCount= 20,
        encoding= u'utf8',
        delay=0,
    )
    info_handler.setFormatter(fr)
    info_handler.setLevel(logging.INFO)
    return info_handler

def get_error_handler():
    filename = PATH + "error-" + date.today().isoformat() + ".log"
    fr = JsonFileFormater(BASIC_FORMAT)
    error_handler = RotatingFileHandler(
        filename,
        maxBytes= 10*1024*1024,
        backupCount= 20,
        encoding= u'utf8',
        delay=0,
    )
    error_handler.setFormatter(fr)
    error_handler.setLevel(logging.ERROR)
    return error_handler

def get_console_handler():
    fr = ConsoleFormater(BASIC_FORMAT)
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(fr)
    console_handler.setLevel(logging.DEBUG)
    return console_handler


if __name__ == '__main__':

    logger = logging.root
    logger.level = logging.NOTSET
    logger.addHandler(get_console_handler())
    logger.addHandler(get_info_handler())
    logger.addHandler(get_error_handler())
    logger.info('info  test')

    try:
        1/0
    except Exception, e:
        import traceback
        err = traceback.format_exc(e)
        logger.warn(err)
